<script setup>
import { useEmployeeStore } from "@/stores/employee.js";
import EmployeeHeader from "@/components/employee/EmployeeHeader.vue";
import EmployeeNoLoginHeader from "@/components/employee/EmployeeNoLoginHeader.vue";
import EmployeeAside from "@/components/employee/EmployeeAside.vue";
import MainPage from "@/components/MainPage.vue";
import instance from "@/utils/request.js";
import { ElMessage } from "element-plus";
import router from "@/router/router.js";

// 员工界面的底层布局容器

const employee = useEmployeeStore();

let beforeUnload_time = ref();
let gap_time = ref();

// 关闭页面清除登录信息
onMounted(() => {
  window.addEventListener("beforeunload", () => beforeunloadHandler());
  window.addEventListener("unload", () => unloadHandler());
})

// 暴露退出方法
provide("exit", exit);

function beforeunloadHandler() {
  beforeUnload_time.value = new Date().getTime();
}

function unloadHandler() {
  gap_time.value = new Date().getTime() - beforeUnload_time.value;
  if(gap_time.value <= 5) {
    exit();
  }
}

function exit() {
  // 退出
  if(employee.employee_id === null) return;
  instance.request({
    url: 'employee/index/exit',
    method: 'POST',
    data: {
      employee_id: employee.employee_id
    },
    headers: { "Employee-Id": employee.employee_id }
  })
      .then(function(response) {
        if(response.data.code === "ERROR") {
          ElMessage({
            message: "退出失败！",
            type: "error"
          });
        }
        if(response.data.code === "SUCCESS") {
          router.push('/employee/index');
          employee.logout();
        }
      })
      .catch(function(error){
        console.log(error);
        ElMessage({
          message: "退出失败！",
          type: "error"
        });
      });
}
</script>

<template>
  <div class="common-layout">
    <el-container class="el-container">
      <el-header height="50px">
        <employee-header v-if="employee.employee_id !== null"/>
        <employee-no-login-header v-if="employee.employee_id === null"/>
      </el-header>

      <el-container>
        <el-aside width="250px" class="el-aside">
          <employee-aside v-if="employee.employee_id !== null"/>
        </el-aside>

        <el-main>
          <main-page/>
        </el-main>

      </el-container>
    </el-container>
  </div>
</template>

<style scoped>
.el-header {
  padding: 0;
}
.el-menu {
  border: 0;
}
.el-main {
  padding: 0;
}
.el-aside {
  background-color: #2a3441;
}
</style>

